package com.example.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.example.entity.Article;
import com.example.entity.Type;
import com.example.entity.User;
import com.example.entity.*;
import com.example.entity.vo.ArticleVo;
import com.example.entity.vo.CommentVO;
import com.example.service.ArticalService;
import com.example.service.UserService;
import com.example.util.BeanFactroy;
import com.example.util.FileUploadUtil;
import com.example.util.QiniuUpload;
import com.example.util.R;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/article/*")
public class ArticalController extends HttpServlet {
    private ArticalService articalservice = BeanFactroy.createBean(ArticalService.class);
    private UserService userService = BeanFactroy.createBean(UserService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();

        if ("/addArticle".equals(path)) {
            addArticle(request, response);
        }else if ("/editorPic".equals(path)){
            editorPic(request, response);
        }

    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();

        if ("/QueryArticalById".equals(path)) {
            QueryArticalById(request, response);
        }
//        else if ("/QueryPerHotArtical".equals(path)) {
//            QueryPerHotArtical(request, response);
//        }
        else if ("/QueryPerAllArtical".equals(path)) {
            QueryPerAllArtical(request, response);
        }
//        else if ("/differTime".equals(path)){
//            differTime(request, response);
//        }
        else if ("/findAriticleBlur".equals(path)) {
            findAriticleBlur(request, response);
        } else if ("/findHotAriticle".equals(path)) {
            findHotAriticle(request, response);
        } else if ("/findType".equals(path)) {
            findType(request, response);
        }else if ("/findHotTitle".equals(path)) {
            findHotTitle(request, response);
        }else if ("/SearchByKey".equals(path)) {
            SearchByKey(request, response);
        }else if ("/addLikes".equals(path)){
            addLikes(request, response);
        }else if ("/reduceLikes".equals(path)){
            reduceLikes(request, response);
        }else if ("/queryColletedArticle".equals(path)){
            queryColletedArticle(request, response);
        }else if ("/updateColletion".equals(path)){
            updateColletion(request, response);
        }else if ("/addColletion".equals(path)){
            addColletion(request, response);
        }else if ("/deleteArticleById".equals(path)){
            deleteArticleById(request, response);
        }
        if ("/isLikes".equals(path)){
            isLikes(request, response);
        }
        if ("/isCollect".equals(path)){
            isCollect(request, response);
        }
    }

    private void deleteArticleById(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException{
        String articleId = request.getParameter("articleId");
        int delete = articalservice.deleteById(Long.parseLong(articleId));
        if (delete == 1){
            response.getWriter().print(JSON.toJSONString(R.ok()));
        }else {
            response.getWriter().print(JSON.toJSONString(R.error()));
        }

    }

    /**
     * 更新收藏 根据用户id和文章id添加收藏
     * @param request
     * @param response
     */
    private void addColletion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Long userId = Long.parseLong(request.getParameter("uid"));
        Long articleId = Long.parseLong(request.getParameter("aid"));

        int i = articalservice.addColletion(userId,articleId);
        response.getWriter().print(JSON.toJSONString(R.ok().data("addCollect",i)));
    }
    /**
     * 取消收藏
     * @param request
     * @param response
     */
    private void updateColletion(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Long userId = Long.parseLong(request.getParameter("uid"));
        Long articleId = Long.parseLong(request.getParameter("aid"));

        int i = articalservice.updateColletion(userId,articleId);

        response.getWriter().print(JSON.toJSONString(R.ok().data("cancelCollect",i)));
    }

    /**
     * 通过用户id查找该用户收藏的文章
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void queryColletedArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String userId = request.getParameter("userId");
        List<Article> articleList =  articalservice.queryColletedByUserId(Long.parseLong(userId));
        if (articleList == null){
            response.getWriter().print(JSON.toJSONString(R.error()));

        }else {
            response.getWriter().print(JSON.toJSONString(R.ok().data("colletions",articleList)));

        }

    }
    /**
     * 模糊搜索
     *
     * @param request
     * @param response
     */
    private void SearchByKey(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String key = request.getParameter("key");
        List<Article> searchVOS = articalservice.SearchByKey(key);
        response.getWriter().print(JSON.toJSONString(R.ok().data("searchVOS",searchVOS)));
    }

    //热搜榜查询
    private void findHotTitle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Article> articles = articalservice.queryHotTitle();
        response.getWriter().print(JSON.toJSONString(R.ok().data("articalsInfo", articles)));
    }

    //查询主页type标签
    private void findType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = articalservice.queryType();
        response.getWriter().print(JSON.toJSONString(R.ok().data("typeList", typeList)));
    }


    //后台按类型搜索热门文章目录
    private void findHotAriticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter("type");
        if (!"".equals(type) && !type.isEmpty()) {
            long type1 = Long.parseLong(type);
            List<Article> articles = articalservice.queryHotArtical(type1);
            response.getWriter().print(JSON.toJSONString(R.ok().data("articalsInfo", articles)));
        }

    }

    //根据id查找文章详情
    private void QueryArticalById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long id = Long.parseLong(request.getParameter("id"));
//        Long id = Long.parseLong("1");
        Article articles = articalservice.QueryArticalById(id);

        List<ArticleVo> Hotarticles = articalservice.QueryArticalByUserId(id);

        //用户信息
        Long userId = articles.getUserId();
        User userInfo = userService.queryUserById(userId);

        //System.out.println(articles);
        //System.out.println(Hotarticles);
        response.getWriter().print(JSON.toJSONString(R.ok().data("HotArticals",Hotarticles).data("articalsInfo", articles).data("userInfo",userInfo)));
//        response.getWriter().print(JSON.toJSONString(R.ok().));
    }

    //查找个人热门文章
//    private void QueryPerHotArtical(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        Long id = Long.parseLong(request.getParameter("id"));
//
//        List<ArticleVo> articles = articalservice.QueryArticalByUserId(id);
//        System.out.println(articles);
//        response.getWriter().print(JSON.toJSONString(R.ok().data("HotArticals", articles)));
//    }

    //查找个人全部文章
    private void QueryPerAllArtical(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long userId = Long.parseLong(request.getParameter("userId"));
//        Long id = Long.parseLong("1");
        List<Article> articles = articalservice.QueryAllArticalByUserId(userId);
        if(articles == null){
            response.getWriter().print(JSON.toJSONString(R.error()));
        }else {
            response.getWriter().print(JSON.toJSONString(R.ok().data("AllArticals", articles)));

        }

    }

    //返回文章时间差值
//    private void differTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        Long id = Long.parseLong("1");
//        int DifferTime= articalservice.differTime(id);
//        System.out.println(DifferTime);
//        response.getWriter().print(JSON.toJSONString(R.ok().data("differTime",DifferTime)));
//    }

    //对文章标题模糊查询
    private void findAriticleBlur(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String str1 = request.getParameter("str");
        //System.out.println(str1);
        List<Article> articalByBlur = articalservice.queryArticalByBlur(str1);
//        System.out.println(str1);
//        System.out.println(articalByBlur);
        response.getWriter().print(JSON.toJSONString(R.ok().data("blurArticle", articalByBlur)));
    }

    //新增文章
    private void addArticle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            HashMap<String, String> map = new HashMap<>();
            StringBuffer buf = new StringBuffer();
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    String fileName = fileItem.getFieldName();
                    String value = fileItem.getString("UTF-8");
                    map.put(fileName, value);
                } else {
                    String fileName = fileItem.getName();
                    String saveFile = FileUploadUtil.randomFilename() + FileUploadUtil.getFileSuffix(fileName);
                    String fileUrl = QiniuUpload.uploadByFile(fileItem.getInputStream(), "toutiao/img/" + saveFile);
                    buf.append(fileUrl + ",");
                }
            }
            String firstImg = buf.toString();
            firstImg = firstImg.substring(0, firstImg.length() - 1);
            String userId = map.get("userId");
            String typeId = map.get("typeId");
            Article article = new Article(
                    map.get("title"),
                    map.get("content"),
                    map.get("flag"),
                    map.get("description"),
                    Long.parseLong(userId),
                    firstImg,
                    Long.parseLong(typeId)
            );
            int res = articalservice.addArticle(article);
            if (res > 0) {
                response.getWriter().print(JSON.toJSONString(R.ok()));
            } else {
                response.getWriter().print(JSON.toJSONString(R.error()));
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //editor上传图片
    private void editorPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (!fileItem.isFormField()) {
                    String fileName = fileItem.getName();
                    String saveFile = FileUploadUtil.randomFilename() + FileUploadUtil.getFileSuffix(fileName);
                    String fileUrl = QiniuUpload.uploadByFile(fileItem.getInputStream(), "toutiao/img/" + saveFile);

                    JSONObject res = new JSONObject();
                    res.set("url",fileUrl);
                    res.set("success", 1);
                    res.set("message", "upload success!");

                    response.getWriter().print(JSONUtil.toJsonStr(res));
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //判断是否点赞
    private void isLikes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long articleId = Long.parseLong(request.getParameter("aid"));
        Long userId = Long.parseLong(request.getParameter("uid"));
        int i = articalservice.isLieks(userId,articleId);
        //System.out.println(i);
        response.getWriter().print(JSON.toJSONString(R.ok().data("islikes",i)));
    }

    //添加点赞数
    private void addLikes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long articleId = Long.parseLong(request.getParameter("aid"));
        Long userId = Long.parseLong(request.getParameter("uid"));
        int i = articalservice.addLikes(userId,articleId);
        //System.out.println(i);
        response.getWriter().print(JSON.toJSONString(R.ok().data("addlikes",i)));
    }

    //取消赞
    private void reduceLikes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long articleId = Long.parseLong(request.getParameter("aid"));
        Long userId = Long.parseLong(request.getParameter("uid"));
        int i = articalservice.reduceLikes(userId,articleId);
        response.getWriter().print(JSON.toJSONString(R.ok().data("reducelikes",i)));
    }


    //判断收藏
    private void isCollect(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long articleId = Long.parseLong(request.getParameter("aid"));
        Long userId = Long.parseLong(request.getParameter("uid"));
        int i = articalservice.isCollect(userId,articleId);
        response.getWriter().print(JSON.toJSONString(R.ok().data("isCollect",i)));
    }
}
